﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infrastructures;
using IRepository;
using Models;

namespace ConcreteService
{
    public abstract class CommonService
    {
        internal CommonService() { }

        public virtual T Create<T>(T obj, string oper)
        {
            if (obj == null || oper == null)
                throw new Exception("Create :: obj or oper is null");
            ICommonRepository repo = ServiceFactory.CreateInstance<ICommonRepository>();
            repo.Create(obj);

            ProcessHelper.ProcessAfterDone(obj, oper.ToString(), EventType.Create, false);

            return obj;
        }

        public virtual void Update<T>(T obj, string oper)
        {
            if (obj == null || oper == null)
                throw new Exception("Update :: obj or oper is null");
            ICommonRepository repo = ServiceFactory.CreateInstance<ICommonRepository>();
            repo.Update(obj);

            ProcessHelper.ProcessAfterDone(obj, oper.ToString(), EventType.Update);
        }

        public virtual void Delete<T>(string code, string oper)
        {
            if (code == null || oper == null)
                throw new Exception("Delete :: code or oper is null");
            var obj = Get<T>(code);
            if (obj == null)
                return;

            ICommonRepository repo = ServiceFactory.CreateInstance<ICommonRepository>();
            repo.Delete<T>(code);

            ProcessHelper.ProcessAfterDelete(code.ToString(), obj, oper.ToString(), EventType.Delete);
        }

        public virtual T Get<T>(string code)
        {
            if (code == null)
                throw new Exception("Get :: code is null");
            var val = CacheManager.Get<T>(code);
            if (val != null)
                return val;

            ICommonRepository repo = ServiceFactory.CreateInstance<ICommonRepository>();
            val = repo.Get<T>(code);

            if (val != null)
                CacheManager.Put(val);

            return val;
        }

        public virtual List<T> List<T>()
        {
            var lst = CacheManager.List<T>();
            if (lst != null && lst.Count != 0)
                return lst;

            ICommonRepository repo = ServiceFactory.CreateInstance<ICommonRepository>();
            return repo.List<T>();
        }
    }
}
